package jh.com.jhappbf.contract;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.PlanModel;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.ExpressionUtils;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.utils.MoneyNumToChinese;

public class ContractAppend extends AbActivity {

    private TextView mTxtPlanId;
    private TextView mTxtReceiver;
    private TextView mTxtPlanMoneyAmount;
    private TextView mTxtCargoname;
    private EditText mTxtPrice;
    private TextView mTxtAppendPlan;
    private EditText mTxtMoney;
    private TextView mTxtType;
    private EditText mTxtMoneyRmb;
    private Context mAppcontext;
    private AbTitleBar mTitleBar;
    private Button mBtnOk;
    private int APPENDPLAN = 0X00001;
    private String mOldMoney = "0";
    private AbLoadDialogFragment mDialogFragment = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAppcontext = getApplicationContext();
        setAbContentView(R.layout.contract_append_activity);
        mTitleBar = getTitleBar();
        mTitleBar.setTitleText("计划追加");
        mTitleBar.setLogo(R.drawable.button_selector_back);
        mTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        ;
        mTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mTitleBar.setLogoLine(R.mipmap.line);
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        mTxtPlanId = findViewById(R.id.contract_append_planid_txt);
        mTxtReceiver = findViewById(R.id.contract_append_receiver_txt);
        mTxtPlanMoneyAmount = findViewById(R.id.contract_append_amount_txt);
        mTxtMoney = findViewById(R.id.contract_append_money_txt);
        mTxtAppendPlan = findViewById(R.id.contract_append_appendplan_txt);
        mTxtPrice = findViewById(R.id.contract_append_price_txt);
        mTxtCargoname = findViewById(R.id.contract_append_cargoname_txt);
        mTxtMoneyRmb = findViewById(R.id.contract_append_money_rmb_txt);
        mTxtType = findViewById(R.id.contract_append_type_txt);
        View rightView = getLayoutInflater().inflate(R.layout.title_right_ok_btn_view, null);
        mTitleBar.addRightView(rightView);
        mBtnOk = rightView.findViewById(R.id.title_right_ok_btn);
        mBtnOk.setOnClickListener(v -> {
            Intent intent = new Intent(ContractAppend.this, PasswordConfirmActivity.class);
            startActivityForResult(intent, APPENDPLAN);

        });

        Intent intent = getIntent();
        PlanModel model = intent.getParcelableExtra("model");
        mTxtPlanId.setText(model.getPlanId());
        mTxtCargoname.setText(model.getCargoname());
        mOldMoney = model.getMoney();
        mTxtPlanMoneyAmount.setText(String.valueOf(mOldMoney));
        mTxtType.setText(model.getType());
        mTxtReceiver.setText(model.getReceiver());
        mTxtPrice.setText(model.getPrice());

        TextWatcher watcher = new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String val = mTxtMoney.getText().toString();
                boolean b = ExpressionUtils.isNumber(val);

                if (ExpressionUtils.isNumber(mOldMoney) && b && !"-".equals(val)) {
                    double oldMoney = Double.parseDouble(mOldMoney);
                    double dAppendMoney = Double.parseDouble(val);
                    NumberFormat nf = NumberFormat.getInstance();
                    nf.setMaximumFractionDigits(3);
                    nf.setGroupingUsed(false);
                    mTxtPlanMoneyAmount.setText(nf.format(dAppendMoney + oldMoney));
                } else {
                    mTxtPlanMoneyAmount.setText(mOldMoney);
                }

                try {
                    String rmb = MoneyNumToChinese.arabNumToChineseRMB(val);
                    mTxtMoneyRmb.setText(rmb);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        mTxtMoney.addTextChangedListener(watcher);
        mTxtPrice.addTextChangedListener(watcher);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == APPENDPLAN && resultCode == RESULT_OK) {
            String id = mTxtPlanId.getText().toString();
            String money = mTxtMoney.getText().toString();
            String price = mTxtPrice.getText().toString();
            if (TextUtils.isEmpty(id)) {
                Toast.makeText(ContractAppend.this, "计划单号不能为空!",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(money)) {
                Toast.makeText(ContractAppend.this, "追加金额不能为空!",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            if (!ExpressionUtils.isNumber(money)) {
                Toast.makeText(ContractAppend.this, "追加金额不合法!",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            operatorServer(id, money);
        }
    }

    /**
     * 第一次加载
     */
    private void operatorServer(final String id, final String money) {
        mDialogFragment = AbDialogUtil.showLoadDialog(ContractAppend.this,
                R.mipmap.ic_load, "操作中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> appendContract(money, id));
    }

    /**
     * 添加计划
     */
    private void appendContract(String amount, String id) {
        String methodName = "AppendPlan";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("planId");
        param.add("appendMoney");
        param.add("user");
        param.add("appUserCode");
        value.add(id);
        value.add(amount);
        value.add(State.mName);

        DecimalFormat dFormat = new DecimalFormat("000");
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        Calendar calendar = Calendar.getInstance();
        String date = timeFormat.format(calendar.getTime());
        String appUserId = State.mApplicationCode + dFormat.format(Integer.parseInt(State.mUserId));
        value.add(appUserId);
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(ContractAppend.this);
            List<JSONObject> newListData = JsonHelper
                    .getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                JSONObject obj = newListData.get(0);
                String value1 = obj.optString("result");
                String memo = obj.optString("memo");
                if ("true".equals(value1)) {
                    ContractAppend.this.setResult(RESULT_OK);
                    Toast.makeText(ContractAppend.this, memo,
                            Toast.LENGTH_SHORT).show();
                    ContractAppend.this.finish();
                } else {
                    Toast.makeText(ContractAppend.this, memo,
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(ContractAppend.this, "操作失败,请重试",
                        Toast.LENGTH_SHORT).show();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(ContractAppend.this);
            Toast.makeText(ContractAppend.this, "操作失败,请重试",
                    Toast.LENGTH_SHORT).show();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppcontext).addRequest(webService);
    }
}
